package cn.mrlong.base.ktnet

import android.util.Log
import kotlinx.coroutines.*

/**
 * 作者：BINGO
 * 时间：2021/04/06 11:11
 */
object N {
    fun <T> executeRequest(request: suspend () -> T?,
                           onSuccess: (T) -> Unit = {},
                           onFail: (Throwable) -> Unit = {}): Job {
        val uiScope = CoroutineScope(Dispatchers.Main)  // UI主线程的CoroutineScope
        return uiScope.launch {
            try {
                val res: T? = withContext(Dispatchers.IO) {
                    request()
                }  // IO线程中执行网络请求，成功后返回这里继续执行
                res?.let {
                    onSuccess(it)
                }
            } catch (e: CancellationException) {
                Log.e("executeRequest", "job cancelled")
            } catch (e: Exception) {
                Log.e("executeRequest", "request caused exception")
                onFail(e)
            }
        }
    }
}